package com.net.xpay.core.helper;

import com.google.common.base.Strings;
import com.net.xpay.core.constant.CoreConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author  on 07/03/2018.
 * url="http://www.yx.cuicanxiu.net/hadad?xxxx=value
 * mainDomain=""cuicanxiu.net
 * subDomain="yx"
 */
@Slf4j
@Component
public class DomainHelper {
    private static final char PATH_SPLITTER = '/'; //domain结尾的分隔符

    private static final char DOMAIN_SPLITTER = '.'; //domain 的分隔符

    private static final String WWW_PREFIX = "www."; //www前缀

    public String getCookieDomain(HttpServletRequest request) {
        String server = request.getServerName();
        log.info("getCookieDomain server ={}", server);
        if (Strings.isNullOrEmpty(server)) {
            return null;
        }

        server = trim(server);

        return server;
    }


    private String getSubDomainField(String server, String domain) {
        String prefix = server.substring(0, server.length() - domain.length());
        if (!prefix.endsWith("" + DOMAIN_SPLITTER) || prefix.equals("" + DOMAIN_SPLITTER)) {
            return null;
        }

        prefix = prefix.substring(0, prefix.length() - 1); //去掉最后的dot

        int index = prefix.lastIndexOf(DOMAIN_SPLITTER); //去掉前面的三级子域名,我们只需要二级子域名
        if (index < 0) {
            return prefix;
        } else {
            return prefix.substring(index);
        }
    }

    /**
     * 去掉开始的http(s)://和结尾的 '/'
     *
     * @param server 域名
     * @return 不包含协议部分的链接
     */
    private String trim(String server) {
        int end = server.length();
        for (int i = server.length() - 1; i >= 0; i--) {
            if (server.charAt(i) != PATH_SPLITTER) {
                break;
            } else {
                end = i;
            }
        }
        server = server.substring(0, end);

        if (server.startsWith(CoreConstant.HTTP_PREFIX)) {
            server = server.substring(CoreConstant.HTTP_PREFIX.length());
        } else if (server.startsWith(CoreConstant.HTTPS_PREFIX)) {
            server = server.substring(CoreConstant.HTTPS_PREFIX.length());
        } else if (server.startsWith(CoreConstant.SCHEME_RELATIVE_PREFIX)) {
            server = server.substring(CoreConstant.SCHEME_RELATIVE_PREFIX.length());
        }

        if (server.startsWith(WWW_PREFIX)) {
            server = server.substring(WWW_PREFIX.length());
        }

        return server;
    }
}
